package cn.antho.basic.controller;

import cn.antho.basic.util.AjaxResult;
import cn.antho.basic.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {

    // 上传接口
    @PostMapping
    public AjaxResult upload(@RequestPart("file") MultipartFile file) throws IOException {
        // 扩展名
        String filename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(filename);
        String address = FastdfsUtil.upload(file.getBytes(), extension);
        return AjaxResult.me().success(address);
    }

    // 删除接口
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "filePath") String filePath){
        // 得到组名
        String pathTmp = filePath.substring(1); // goup1/xxxxx/yyyy
        String groupName =  pathTmp.substring(0, pathTmp.indexOf("/"));
        // 得到图片路径
        String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);
        // 传递组名和图片路径名称，调用工具类方法进行删除
        FastdfsUtil.delete(groupName, remotePath);
        return AjaxResult.me().success();
    }

}
